# encoding: utf-8
require 'utils'

class UserController < ApplicationController
  before_filter :login_required, :only => [:update]

  def reviews
    
  end

  def create
    logout_keeping_session!

    @user = User.new(params[:user])
    
    if failed_login(params[:user])
    	flash[:error] = "注册失败！请填写正确的信息再提交。"
      render :action => 'new' and return
    end
    
    if @user && @user.save && @user.errors.empty?
      redirect_back_or_default('/')
      flash[:notice] = "感谢你的注册!  我们已经发送激活码到你的邮箱。"
    else
      flash[:error] = "注册失败！请填写正确的信息再提交。"
      render :action => 'new'
    end
  end

  def update
    @user = User.find(params[:id])
    @user.update_attributes(params[:user])
  end
  
  def activate
    logout_keeping_session!
    user_verify = UserVerify.find_by_verify_code(params[:activation_code]) unless params[:activation_code].blank?
    case
    when (!params[:activation_code].blank?) && user_verify
      user_verify.user.activate!
      flash[:notice] = "激活帐号完成! 请登录继续."
      redirect_to '/login'
    when params[:activation_code].blank?
      flash[:error] = "验证码不能为空.  请点击你注册邮箱的激活链接."
      redirect_back_or_default('/')
    else 
      flash[:error]  = "激活帐号失败。请检查你注册邮箱的激活链接或者您已经激活。"
      redirect_back_or_default('/')
    end
  end
  
  protected

  def failed_login(params)

    if !Utils.match_email? params[:email]
      @error = "请输入你的Email(电子邮件)地址"
    elsif params[:nick_name].blank?
      @error = "请输入你的名号"
    elsif params[:password].blank? or params[:password].length < 6
      @error = "请给自己设一个密码(6字母以上)"
    elsif params[:password_confirmation].blank?
      @error = "请输入确认密码"
    elsif params[:password] != params[:password_confirmation]
      @error = "密码和确认密码不相等"
    end
    @error ? true : false
  end

end
